

import React, { useEffect, useState } from 'react'
import { Upload, message,Form,Button,Input,Select  } from 'antd';
import ImgCrop from 'antd-img-crop';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { useDispatch, useSelector } from 'react-redux';
import { httpcheckNameNum, httpGetUserInfoById, httpUpdateUserInfo } from '../../apis';
import { setUser } from "../../store/action"
import { fetchUserFromStorage, setUserStorage } from '../../utils/storage';
import "./ChangeInfo.scss"
import { BASE_ADDR } from '../../apis/http';

const { Option } = Select;


function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}


export default function ChangeInfo() {
      const [loading,setLoading] = useState(false);
      const [imageUrl,setImageUrl] = useState(null);
      const user = fetchUserFromStorage();
      const dispatch = useDispatch();
      const handleChange = async info => {
        if (info.file.status === 'uploading') {
          setLoading(true);
          return;
        }
        if (info.file.status === 'done') {
          getBase64(info.file.originFileObj, (imageUrl) => {
            setLoading(false);
            setImageUrl(imageUrl);
          });
          message.success("上传头像成功~");
          let data = {};
          data.userId = user.userId;
          let userInfo = await httpGetUserInfoById(data);
          dispatch(setUser(userInfo))
          setUserStorage(userInfo);
        }
      };
      const onFinish = async (values) => {
        values.userId = user.userId;
        let res = await httpUpdateUserInfo(values);
        if(res===1) {
          for(let x in values) {
            user[x] = values[x];
          }
          dispatch(setUser(user));
          setUserStorage(user);
          message.success("修改用户信息成功!");
        } else {
          message.error("修改用户信息错误!");
        }
      }
      const validateName = async (rule,val) => {
        let data = {};
        data.name = val;
        data.userId = user.userId;
        let res = await httpcheckNameNum(data);
        console.log(res);
        if(res) {
          console.log("用户名重复")
          return Promise.reject("用户名已重复");
        } else {
          return Promise.resolve();
        }
      }
      const uploadButton = (
        <div>
          {loading ? <LoadingOutlined /> : <PlusOutlined />}
          <div style={{ marginTop: 8 }}>Upload</div>
        </div>
      );
      return (
        <div className='ChangeInfo-container'>
        <ImgCrop rotate>
          <Upload
            action={`${BASE_ADDR}video/user/uploadAvatar`}
            listType="picture-card"
            name={`${user.userId}`}
            showUploadList={false}
            onChange={handleChange}
          >
              {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
          </Upload>
        </ImgCrop>
        <div className='form-container'>
          <Form
            name="basic"
            labelCol={{ span: 10 }}
            wrapperCol={{ span: 30 }}
            onFinish={onFinish}
            initialValues={user}
            autoComplete="off"
          >
            <Form.Item
              label="用户名"
              name="name"
              rules={[{ required: true, message: '请输入你的用户名' },
            {
              validator: validateName
            }]}
            >
              <Input/>
            </Form.Item>

            <Form.Item
              label="用户签名"
              name="description"
            >
              <Input.TextArea showCount maxLength={100} />
            </Form.Item>


            <Form.Item
              name="email"
              label="E-mail"
              rules={[
                {
                  type: 'email',
                  message: 'The input is not valid E-mail!',
                },
                {
                  required: true,
                  message: 'Please input your E-mail!',
                },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              name="age"
              label="Age"
              rules={[
                {
                  required: true,
                  message: 'Please input your E-mail!',
                },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              name="sex"
              label="gender"
              rules={[
                {
                  required: true,
                  message: 'Please select gender!',
                },
              ]}
            >
              <Select placeholder="select your gender">
                <Option value="male">Male</Option>
                <Option value="female">Female</Option>
                <Option value="other">Other</Option>
              </Select>
            </Form.Item>

            <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
              <Button type="primary" htmlType="submit">
                保存信息
              </Button>
            </Form.Item>
          </Form>
        </div>

        </div>
      );
}
